package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;


    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }


    @Override
    public void save(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            bpmnInfoMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    public void deploy(String path, String bpmnType, String info) throws FileNotFoundException {
        // 根据文件路径找到文件(前面是父，后面是子，拼接起来)
        File bpmnFile = new File(SystemConfig.getProfile(), path);
        // 将文件部署到activiti中
        Deployment deploy = repositoryService.createDeployment()// 部署流程
                .addInputStream(path, new FileInputStream(bpmnFile))// 名称一般使用路径，
                .deploy();
        // 创建流程定义对象，封装字段信息
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setBpmnType(bpmnType); //流程类型
        bpmnInfo.setInfo(info); // 备注信息
        bpmnInfo.setDeploymentId(deploy.getId()); // 部署id
        bpmnInfo.setDeployTime(new Date()); // 部署时间
        // 获取流程定义对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploy.getId())
                .singleResult();
        bpmnInfo.setActProcessId(processDefinition.getId()); // 定义id
        bpmnInfo.setActProcessKey(processDefinition.getKey()); // 定义key
        bpmnInfo.setBpmnName(processDefinition.getName()); // 定义名称
        // 保存到数据库中
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public InputStream getResourceAsStream(String deploymentId, String type) {
        // 获取流程定义对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploymentId)
                .singleResult();
        // 判断
        if ("xml".equalsIgnoreCase(type)){
            // xml文件
            String resourceName = processDefinition.getResourceName();
            //把哪个对象中的那个属性装换成流（根据资源名称获取输入流）
            return repositoryService.getResourceAsStream(deploymentId,resourceName);
        }else {
            // png
            // 根据定义的id来获取model（模型都有哪些节点）
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            // generateDiagram(bpmn模板对象，需要高亮的节点，需要高亮的线桥)
            return generator.generateDiagram(bpmnModel, Collections.EMPTY_LIST, Collections.EMPTY_LIST,"宋体","宋体","宋体");
        }
    }

    @Override
    @Transactional
    public void delete(Long id) {
        // 根据id获取bpmnInfo对象
        BpmnInfo bpmnInfo = this.get(id);
        // 删除bpmnInfo对象
        bpmnInfoMapper.deleteByPrimaryKey(id);
        // 查询这个流程定义还在运行的流程实例
        // 把流程实例关联的 找到业务对象
        // 获取流程定义对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(bpmnInfo.getDeploymentId())
                .singleResult();
        // 删除activiti中的流程定义对象
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(),true);
        // 把服务器中的文件删除掉
        String resourceName = processDefinition.getResourceName();
        File file = new File(SystemConfig.getProfile(), resourceName);
        if (file.exists()){
            file.delete();
        }
    }

    @Override
    public BpmnInfo getByBpmnType(String type) {
        return bpmnInfoMapper.getByBpmnType(type);
    }
}
